from PyQt6.QtWidgets import QTextEdit, QPushButton, QVBoxLayout, QWidget, QMessageBox
import sqlite3
import pandas as pd  # 新增导入

class SyntaxEditor(QWidget):
    def __init__(self):
        super().__init__()
        self.editor = QTextEdit()
        self.run_button = QPushButton("执行 SQL")
        self.run_button.clicked.connect(self.run_sql)

        layout = QVBoxLayout()
        layout.addWidget(self.editor)
        layout.addWidget(self.run_button)
        self.setLayout(layout)

        self.db_conn = None
        self.result_tab = None

    def set_connection(self, conn, result_tab):
        self.db_conn = conn
        self.result_tab = result_tab

    def run_sql(self):
        if not self.db_conn:
            QMessageBox.warning(self, "未连接", "请先连接数据库")
            return
        sql = self.editor.toPlainText()
        try:
            cursor = self.db_conn.cursor()
            cursor.execute(sql)
            if sql.strip().lower().startswith("select"):
                columns = [desc[0] for desc in cursor.description]
                rows = cursor.fetchall()
                df = pd.DataFrame(rows, columns=columns)
                self.result_tab.show_results([df], "查询成功")
            else:
                self.db_conn.commit()
                QMessageBox.information(self, "成功", "执行成功")
        except Exception as e:
            QMessageBox.critical(self, "错误", str(e))
